import router from "@/router/index";
import store from '@/store'

router.beforeEach((to, from, next) => {
  const whiteList = ['/login']
  let token = sessionStorage.getItem("token");  //正常拿到Vuex里面的tokens
  // let token = store.getters.GET_TOKEN;  //正常拿到Vuex里面的tokens
  let menuList = store.getters.GET_MENULIST
  let hasRoutes = store.state.hashRoutes;
  if (token) {
    if (!hasRoutes) { //如果第一次没有动态路由 我们要手动绑定
      bindRoute(menuList)
      store.commit("SET_HASROUTES_STATUS", true);
      // next({ path: to.path, query: to.query }) //强制刷新当前页面
      next({ ...to, replace: true })
    } else {
      next()
    }
    // if (to.path !== "/login") {
    //   if (!hasRoutes) {
    //     bindRoute(menuList).then(res => {
    //       store.commit("SET_HASROUTES_STATUS", true);
    //       next({ path: to.path, query: to.query })
    //     })
    //   } else {
    //     next();
    //   }
    // } else if (whiteList.includes(to.fullPath)) {
    //   next(from.path)
    // } else {
    //   next()
    // }
  } else {
    if (whiteList.includes(to.fullPath)) {
      next()
    } else {
      next('/login')
    }
  }
})

//动态绑定路由
let bindRoute = (menuList) => {
  let newRoutes = router.options.routes;
  menuList.forEach(menu => {
    if (menu.children) {
      menu.children.forEach((m) => {
        let route = menuToRoute(m, menu.name)
        if (route) {
          newRoutes[0].children.push(route)
        }
      })
    }
  })
  //重新添加到路由管理中
  newRoutes.forEach(route => {
    router.addRoute(route)
  })
}

// //动态绑定路由
// let bindRoute = (menuList) => {
//   return new Promise((ren, inj) => {
//     let newRoutes = router.options.routes;
//     menuList.forEach(menu => {
//       if (menu.children) {
//         menu.children.forEach((m) => {
//           let route = menuToRoute(m, menu.name)
//           if (route) {
//             newRoutes[0].children.push(route)
//           }
//         })
//       }
//     })
//     //重新添加到路由管理中
//     newRoutes.forEach(route => {
//       router.addRoute(route)
//     })
//     ren(true);
//   })
// }


//菜单转化成路由兑现
const menuToRoute = (menu, parentName) => {
  if (!menu.component) {
    return null;
  } else {
    let route = {
      name: menu.name,
      path: menu.path,
      meta: {
        parentName: parentName
      }
    }
    route.component = () => import('@/views/' + menu.component + '.vue')
    return route;
  }
}